package com.hujesse.controller;

import com.google.gson.Gson;
import com.hujesse.pojo.Dept;
import com.hujesse.service.DeptServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

// C:\Windows\System32\drivers\etc
@RestController
public class DeptController {
    @Autowired
    private DeptServiceImpl deptService;
    @Autowired
    private DiscoveryClient client;

    // 添加一个部门
    @PostMapping("/add")
    public String addDept(@RequestBody Dept dept){
        boolean save = deptService.save(dept);
        return save==true?"ok":"false";
    }
    // 根据id查询部门
    @GetMapping("/get/{id}")
    public String getId(@PathVariable("id") Long id){
        return  new Gson().toJson(deptService.getById(id));
    }
    @GetMapping("/dept/list")
    public String getList(){
        List<Dept> list = deptService.list();
        return new Gson().toJson(list);

    }
    @GetMapping("/dept/discovery")
    public Object discovery() {
        // 获取微服务列表的清单
        List<String> services = client.getServices();
        System.out.println("discovery=>services:" + services);
        // 得到一个具体的微服务信息,通过具体的微服务id，applicaioinName；
        List<ServiceInstance> instances = client.getInstances("springcloud-provider-dept8001");
        for (ServiceInstance instance : instances) {
            System.out.println(
                    instance.getHost() + "\t" + // 主机名称
                            instance.getPort() + "\t" + // 端口号
                            instance.getUri() + "\t" + // uri
                            instance.getServiceId() // 服务id
            );
        }
        return this.client;
    }

}
